<template>
  <div class="contract-advanc-setting" v-loading="loading">
    <div class="contract-advanc-setting-con">
      <!-- 产品质保 -->
      <div class="contract-advanc-setting-con-item">
        <contract-advance-setting-title :switchControl="contractProductQuality.productQualitySwitch" @handleChangeSwitch="handleChangeSwitch($event, '1')">{{ $t('contract.setting.contractAdvancedSettings.updateProductWarrantyInformation') }}</contract-advance-setting-title>

        <div class="contract-advanc-setting-con-item-option" v-if="contractProductQuality.productQualitySwitch">
          <el-select v-model="contractProductQuality.productQualityCondition1" :placeholder="$t('contract.setting.contractAdvancedSettings.pleaseSelect')" size="large">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          {{ $t('contract.setting.contractAdvancedSettings.adopt') }}
          <el-select v-model="contractProductQuality.productQualityCondition2" :placeholder="$t('contract.setting.contractAdvancedSettings.pleaseSelect')" size="large">
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          {{ $t('contract.setting.contractAdvancedSettings.text1') }}
        </div>
        <div v-if="contractProductQuality.productQualityCondition2 != 'PRODUCT_SERVICE_PROJECT' && contractProductQuality.productQualitySwitch">
          <contract-advance-setting-dropDown class="contract-advanc-setting-con-item-option" :value="contractProductQuality.qualityStartDate" :optionsList="contractSubDateFields" @handleChangeDropDown="handleChangeProductQualityDropDown($event, 'start')">
            <template #frontTip>{{ $t('contract.setting.contractAdvancedSettings.text2') }} </template>
            <template #behindTip> {{ $t('contract.setting.contractAdvancedSettings.text3') }}</template>
          </contract-advance-setting-dropDown>
          <contract-advance-setting-dropDown class="contract-advanc-setting-con-item-option" :value="contractProductQuality.qualityEndDate" :optionsList="contractSubDateFields" @handleChangeDropDown="handleChangeProductQualityDropDown($event, 'end')">
            <template #frontTip>{{ $t('contract.setting.contractAdvancedSettings.text2') }} </template>
            <template #behindTip> {{ $t('contract.setting.contractAdvancedSettings.text4') }}</template>
          </contract-advance-setting-dropDown>
        </div>
      </div>

      <!-- 产品质保服务项目 -->
      <div class="contract-advanc-setting-con-item mt_20" v-if="isBgiSaas">
        <contract-advance-setting-title :switchControl="contractQualityServiceItems.serviceItemsSwitch" @handleChangeSwitch="handleChangeSwitch($event, '2')">{{ $t('contract.setting.contractAdvancedSettings.text5') }}</contract-advance-setting-title>

        <div class="contract-advanc-setting-con-item-option" v-if="contractQualityServiceItems.serviceItemsSwitch">
          <el-select v-model="contractQualityServiceItems.serviceItemsCondition1" class="m-2" :placeholder="$t('contract.setting.contractAdvancedSettings.pleaseSelect')" size="large">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          {{ $t('contract.setting.contractAdvancedSettings.text6') }}
        </div>
      </div>

      <!-- 合同生成后触发计划任务 -->
      <div class="contract-advanc-setting-con-item mt_20" v-if="isBgiSaas">
        <contract-advance-setting-title :switchControl="contractTriggerPlanTask.triggerPlanTaskSwitch" @handleChangeSwitch="handleChangeSwitch($event, '3')">{{ $t('contract.setting.contractAdvancedSettings.text7') }}</contract-advance-setting-title>

        <div v-if="contractTriggerPlanTask.triggerPlanTaskSwitch">
          <div class="contract-advanc-setting-con-item-option">
            {{ $t('contract.setting.contractAdvancedSettings.text8') }}
            <el-select v-model="contractTriggerPlanTask.triggerPlanTaskCondition1" class="m-2" :placeholder="$t('contract.setting.contractAdvancedSettings.pleaseSelect')" size="large">
              <el-option v-for="item in taskTypes" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            {{ $t('contract.setting.contractAdvancedSettings.text9') }}
          </div>
          <contract-advance-setting-dropDown class="contract-advanc-setting-con-item-option" :value="contractTriggerPlanTask.triggerPlanTaskStartDate" :optionsList="contractPlanSubDateFields" @handleChangeDropDown="handleChangePlanTaskDropDown($event, 'start')">
            <template #frontTip>{{ $t('contract.setting.contractAdvancedSettings.text11') }} </template>
            <template #behindTip> {{ $t('contract.setting.contractAdvancedSettings.text12') }}</template>
          </contract-advance-setting-dropDown>
          <contract-advance-setting-dropDown class="contract-advanc-setting-con-item-option" :value="contractTriggerPlanTask.triggerPlanTaskEndDate" :optionsList="contractPlanSubDateFields" @handleChangeDropDown="handleChangePlanTaskDropDown($event, 'end')">
            <template #frontTip>{{ $t('contract.setting.contractAdvancedSettings.text11') }} </template>
            <template #behindTip> {{ $t('contract.setting.contractAdvancedSettings.text13') }}</template>
          </contract-advance-setting-dropDown>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs, onMounted, computed, watch } from 'vue';

// components
import ContractAdvanceSettingTitle from './ContractAdvanceSettingTitle.vue';
import ContractAdvanceSettingDropDown from './ContractAdvanceSettingDropDown.vue';

// api
import { contractFieldList, getTaskTypeList } from '@src/api/ContractApi';

import { toast } from '@src/util/platform';

import { options } from '@src/modules/contract/contractList/fields.js';

import _ from 'lodash';
import i18n from '@src/locales';
import { getRootWindow } from '@src/util/dom';

export default defineComponent({
  name: 'contract-advanc-setting',
  components: {
    ContractAdvanceSettingTitle,
    ContractAdvanceSettingDropDown,
  },
  props: {
    settingList: {
      type: Object,
      default: () => ({}),
    },
    contractTemplateId: {
      type: String,
      default: '',
    },
  },
  emits: ['submit'],
  setup(props, { emit }) {
    const loading = ref(true);

    const state = reactive({
      // 产品质保
      contractProductQuality: {
        productQualitySwitch: false,
        productQualityCondition1: '',
        productQualityCondition2: '',
        qualityStartDate: '',
        qualityEndDate: '',
      },
      // 产品质保服务项目
      contractQualityServiceItems: {
        serviceItemsSwitch: false,
        serviceItemsCondition1: '',
      },
      // 合同触发计划任务
      contractTriggerPlanTask: {
        triggerPlanTaskSwitch: false,
        triggerPlanTaskCondition1: '',
        triggerPlanTaskStartDate: '',
        triggerPlanTaskEndDate: '',
      },

      contractFields: [],
      taskTypes: [],
    });

    watch(
      () => props.settingList,
      curVal => {
        state.contractProductQuality = {
          productQualitySwitch: curVal?.proQualityInfo?.productQualitySwitch || false,
          productQualityCondition1: curVal?.proQualityInfo?.productQualityCondition1 || '',
          productQualityCondition2: curVal?.proQualityInfo?.productQualityCondition2 || '',
          qualityStartDate: curVal?.proQualityInfo?.qualityStartDate?.fieldName || '',
          qualityEndDate: curVal?.proQualityInfo?.qualityEndDate?.fieldName || '',
        };

        state.contractQualityServiceItems = {
          serviceItemsSwitch: curVal?.qualityService?.serviceItemsSwitch || false,
          serviceItemsCondition1: curVal?.qualityService?.serviceItemsCondition1 || '',
        };

        state.contractTriggerPlanTask = {
          triggerPlanTaskSwitch: curVal?.planTask?.triggerPlanTaskSwitch || false,
          triggerPlanTaskCondition1: curVal?.planTask?.triggerPlanTaskCondition || '',
          triggerPlanTaskStartDate: curVal?.planTask?.triggerPlanTaskStartDate?.fieldName || '',
          triggerPlanTaskEndDate: curVal?.planTask?.triggerPlanTaskEndDate?.fieldName || '',
        };
      },
      { immediate: true, deep: true }
    );

    // 产品质保开始结束下拉框数据
    const contractSubDateFields = computed(() => {
      return state.contractFields.find(v => v?.formType === 'product')?.subFormFieldList?.filter(v => v.formType === 'date' && (!v.setting?.dateType || v.setting?.dateType === 'yyyy-MM-dd')) || [];
    });

    // 计划开始结束下拉框数据
    const contractPlanSubDateFields = computed(() => {
      return state.contractFields.filter(v => v.fieldName == 'effectiveTime' || v.fieldName == 'invalidTime') || [];
    });

    // 华大基因灰度
    const isBgiSaas = computed(() => {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.bgiSaas)
    })

    const options1 = computed(() => {
      let selectList = [
        {
          value: 'PRODUCT_SERVICE_DATE',
          label: i18n.t('contract.setting.contractAdvancedSettings.productServiceTime'),
        }
      ]
      
      const selectListService = [
        ...selectList,
        {
          value: 'PRODUCT_SERVICE_PROJECT',
          label: i18n.t('contract.setting.contractAdvancedSettings.productServiceProject'),
        }
      ]
      
      return isBgiSaas.value ? selectListService: selectList;

    })

    // 获取合同表单
    const getContractFields = async () => {
      loading.value = true;
      try {
        let ret = await contractFieldList({
          templateId: props.contractTemplateId,
        });

        const { success, message, result } = ret || {};

        if (!success) return toast(message, 'error');

        state.contractFields = result || [];
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        loading.value = false;
      }
    };

    // 获取工单类型
    const fetchTaskPlanList = () => {
      getTaskTypeList({}).then(res => {
        if (!res.success) return toast(res.message, 'error');

        state.taskTypes = res.result;
      });
    };

    // 切换开关
    const handleChangeSwitch = (val, param) => {
      if (param === '1') {
        state.contractProductQuality.productQualitySwitch = val;
      } else if (param === '2') {
        state.contractQualityServiceItems.serviceItemsSwitch = val;
      } else {
        state.contractTriggerPlanTask.triggerPlanTaskSwitch = val;
      }
    };

    // 切换下拉框
    const handleChangeProductQualityDropDown = (val, param) => {
      if (param === 'start') {
        state.contractProductQuality.qualityStartDate = val;
      } else if (param === 'end') {
        state.contractProductQuality.qualityEndDate = val;
      }
    };

    // 切换计划任务
    const handleChangePlanTaskDropDown = (val, param) => {
      if (param === 'start') {
        state.contractTriggerPlanTask.triggerPlanTaskStartDate = val;
      } else if (param === 'end') {
        state.contractTriggerPlanTask.triggerPlanTaskEndDate = val;
      }
    };

    // 数据处理方法
    const dataProcessFunc = (list, currentVal) => {
      const ret = list
        .filter(item => {
          return item.fieldName == currentVal;
        })
        .map(v => {
          return {
            id: v.id,
            fieldName: v.fieldName,
            displayName: v.displayName,
          };
        });

      return ret;
    };

    // 保存 - 提交
    const submit = () => {
      return {
        step: '2',
        params: paramsFunc(),
      };
    };

    const paramsFunc = () => {
      const params = {
        // 产品质保
        proQualityInfo: {
          productQualitySwitch: state.contractProductQuality.productQualitySwitch || false,
          productQualityCondition1: state.contractProductQuality.productQualityCondition1 || null,
          productQualityCondition2: state.contractProductQuality.productQualityCondition2 || null,
          qualityStartDate: dataProcessFunc(contractSubDateFields.value, state.contractProductQuality.qualityStartDate)[0] || null,
          qualityEndDate: dataProcessFunc(contractSubDateFields.value, state.contractProductQuality.qualityEndDate)[0] || null,
        },
        // 产品质保服务
        qualityService: {
          serviceItemsSwitch: state.contractQualityServiceItems.serviceItemsSwitch || false,
          serviceItemsCondition1: state.contractQualityServiceItems.serviceItemsCondition1 || null,
        },
        // 计划任务
        planTask: {
          triggerPlanTaskSwitch: state.contractTriggerPlanTask.triggerPlanTaskSwitch || false,
          triggerPlanTaskCondition: state.contractTriggerPlanTask.triggerPlanTaskCondition1 || null,
          triggerPlanTaskStartDate: dataProcessFunc(contractPlanSubDateFields.value, state.contractTriggerPlanTask.triggerPlanTaskStartDate)[0] || null,
          triggerPlanTaskEndDate: dataProcessFunc(contractPlanSubDateFields.value, state.contractTriggerPlanTask.triggerPlanTaskEndDate)[0] || null,
        },
      };
      return params;
    };

    // 检查内容是否有修改 (暴露的方法)
    const checkModified = () => {
      return JSON.stringify(props.settingList) != JSON.stringify(paramsFunc());
    };

    onMounted(() => {
      getContractFields();
      fetchTaskPlanList();
    });

    return {
      loading,
      options,
      options1,
      contractSubDateFields,
      contractPlanSubDateFields,
      ...toRefs(state),
      handleChangeSwitch,
      handleChangeProductQualityDropDown,
      handleChangePlanTaskDropDown,
      submit,
      checkModified,
      isBgiSaas
    };
  },
});
</script>

<style lang="scss" scoped>
.contract-advanc-setting {
  width: 100%;
  min-height: calc(100vh - 48px);
  padding: 12px;

  &-con {
    width: 100%;
    min-height: calc(100vh - 72px);
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;

    &-item {
      position: relative;
      padding-bottom: 4px;
      &::before {
        content: '';
        display: inline-block;
        width: 2px;
        height: 15px;
        position: absolute;
        top: 4px;
        left: -8px;
        background: $color-primary-light-6;
        border-radius: 2px;
      }
      border-bottom: 1px dashed #e6e6e6;

      &:last-child {
        border-bottom: none;
      }

      &-option {
        font-size: 14px;
        color: #595959;
        font-family: PingFangSC-Regular, PingFang SC;
        margin-bottom: 16px;
      }
    }
  }
}
</style>
